package top.hkyzf.study.leetcode.hash;

import org.junit.Test;

import java.util.*;

/**
 * @author 朱峰
 * @date 2022-1-23 14:44
 */
public class 股票价格波动_2034 {
    @Test
    public void testStockPrice () {
        StockPrice stockPrice = new StockPrice();
        stockPrice.update(1, 10);
        stockPrice.update(2, 5);
        System.out.println(stockPrice.current());
        System.out.println(stockPrice.maximum());
        stockPrice.update(1, 3);
        System.out.println(stockPrice.maximum());
        stockPrice.update(4, 2);
        System.out.println(stockPrice.minimum());
    }
}

class StockPrice {
    Map<Integer, Integer> map = new HashMap<>();
    TreeMap<Integer, Integer> prices = new TreeMap<>();
    int current = 0;

    public StockPrice() {

    }

    public void update(int timestamp, int price) {
        current = Math.max(current, timestamp);
        if (map.containsKey(timestamp)) {
            int old = map.get(timestamp);
            int count = prices.get(old);
            if (count == 1) {
                prices.remove(old);
            } else {
                prices.put(old, count - 1);
            }
        }
        map.put(timestamp, price);
        prices.put(price, prices.getOrDefault(price, 0) + 1);
    }

    public int current() {
        return map.get(current);
    }

    public int maximum() {
        return prices.lastKey();
    }

    public int minimum() {
        return prices.firstKey();
    }
}
